<template>
  <common-edit-dialog
    title="数据集选择"
    :visible="isDataSetDialog"
    @submit="confirmDataSet"
    @cancel="cancelDataSet"
  >
    <div class="choose-dataset-wrap">
      <div class="data-tree" v-loading="isDataSetLoading">
        <common-tree
          searchPlaceholder="查询数据集"
          :tree-data="treeData"
          :tree-prop="{ isLeaf: 'leaf' }"
          :is-slot="true"
          @handleNodeClick="datasetChange"
          :current-node-key="currentDataSet ? currentDataSet.id : null"
          is-show-icon-for-no-child
          set-node-by-key="leaf"
        >
          <div slot-scope="{ scope }" class="tree-item-wrap">
            <svg v-if="scope.data.leaf" class="pre-icon">
              <use xlink:href="#icon-rili-copy"></use>
            </svg>
            <common-carousel-text
              class="tree-label"
              :content="scope.data.name"
            ></common-carousel-text>
          </div>
        </common-tree>
      </div>
      <div class="data-preview">
        <div class="preview-tips">
          <span>仅展示部分数据</span>
        </div>
        <common-table
          class="preview-table"
          :data="datasetData"
          :field="datasetField"
          v-loading="isPreviewDataLoading"
        >
          <!--          <el-table-column v-for="field in datasetField"
                                     :key="field.fieldName"
                                     :prop="field.fieldName"
                                     :label="field.fieldDescribe"
                                     show-tooltip-when-overflow>
                    </el-table-column>-->
        </common-table>
      </div>
    </div>
  </common-edit-dialog>
</template>

<script>
import {
  getPreviewReportsData,
  queryAllTreeWithData,
} from "@/api/screenConfig/dataSet";
import { transformFieldType } from "@/utils";
import { handleTableData } from "../utils";
import { md5 } from "@/utils/aesUtils";
import object from "element-resize-detector/src/detection-strategy/object";

export default {
  name: "DataSetDialog",
  name: "FieldConfigContainer",
  props: {
    datasetName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isDataSetDialog: false, // 是否显示
      isDataSetLoading: false, // 请求数据集列表 loading
      isPreviewDataLoading: false, // 请求预览数据 loading
      currentDataSet: null, // 当前选中的数据集id
      treeData: [],
      datasetField: [],
      datasetData: [],
    };
  },
  methods: {
    cancelDataSet() {
      if (this.datasetName) {
        this.isDataSetDialog = false;
      } else {
        this.$GlobalErrorMessage("请选择数据集");
        this.isDataSetDialog = false;
        this.$parent.$parent.back();
      }
    },
    show() {
      this.isDataSetDialog = true;
      this.getDataSetTreeData();
    },
    getDataSetTreeData() {
      this.isDataSetLoading = true;
      queryAllTreeWithData({ status: 0, classType: 0 })
        .then((res) => {
          if (res && res.code === 200) {
            this.treeData = [
              {
                id: "0-0",
                name: "预定义", // 名称
                isDefault: 1, // 1 预定义 0 自定义
                leaf: false, // false 分类 true 数据集
                children: res.data.filter((item) => item.isDefault === 1),
              },
              {
                id: "0-1",
                name: "自定义",
                isDefault: 0,
                leaf: false,
                children: res.data.filter((item) => item.isDefault === 0),
              },
            ];

            if (res.data.length) {
              // this.datasetChange({ node: res.common[0].children[0] })
            }
          } else {
            this.treeData = [
              {
                name: "预定义", // 名称
                isDefault: 1, // 1 预定义 0 自定义
                leaf: false, // false 分类 true 数据集
                children: [],
              },
              {
                name: "自定义",
                isDefault: 0,
                leaf: false,
                children: [],
              },
            ];
          }
        })
        .finally(() => {
          this.isDataSetLoading = false;
        });
    },
    datasetChange({ data }) {
      this.currentDataSet = data;
      // this.getDataSetData(data.id)
      if (data.leaf) {
        this.getDataSetData(data.id);
      } else {
        this.datasetData = [];
        this.datasetField = [];
        this.datasetTotal = 0;
      }
    },
    getDataSetData(id) {
      this.isPreviewDataLoading = true;
      this.getDataSetById(id)
        .then((res) => {
          let { datasetData, datasetField, datasetTotal } = res;
          this.datasetData = handleTableData(datasetData);
          this.datasetField = datasetField.reduce((r, c) => {
            r.push({
              ...c,
              prop: c.fieldName,
              label: c.fieldDescribe,
              showTooltipWhenOverflow: true,
            });
            return r;
          }, []);

          //show-tooltip-when-overflow
          this.datasetTotal = datasetTotal;
        })
        .finally(() => {
          this.isPreviewDataLoading = false;
        });
    },
    getDataSetById(id) {
      return new Promise((resolve, reject) => {
        getPreviewReportsData({
          datasetId: id,
        }).then((res) => {
          if (res && res.code === 200) {
            let { dataField = [], dataList = [], total = 0 } = res.data;
            let datasetField = [];
            if (dataField) {
              datasetField = dataField.reduce((r, c) => {
                let field = {
                  ...c,
                  originalType: c.fieldType,
                  fieldType: transformFieldType(c.fieldType),
                };
                field.key = md5(
                  `${field.fieldName}_${field.fieldDescribe}_${field.fieldType}`
                );
                r.push(field);
                return r;
              }, []);
            }

            resolve({
              datasetField: datasetField,
              datasetData: dataList,
              datasetTotal: total,
            });
          } else {
            resolve({
              datasetField: [],
              datasetData: [],
              datasetTotal: 0,
            });
          }
        });
      });
    },
    confirmDataSet() {
      if (this.currentDataSet) {
        this.isDataSetDialog = false;
        this.$emit("change", {
          id: this.currentDataSet.id,
          name: this.currentDataSet.name,
          field: this.datasetField,
          list: this.datasetData,
          total: this.datasetTotal,
        });
      } else {
        this.$GlobalErrorMessage("请先选择数据集!");
      }
    },
  },
};
</script>

<style scoped lang="scss">
.choose-dataset-wrap {
  width: 100%;
  height: 476px;
  display: flex;

  .data-tree {
    width: 199px;
    height: 100%;
    border-right: 1px solid #eee;
    padding-right: 18px;
    box-sizing: border-box;
    overflow-y: scroll;

    .tree-item-wrap {
      display: flex;
      align-items: center;
      width: 100%;

      .tree-label {
        margin-left: 4px;
      }

      .pre-icon {
        width: 12px;
        height: 12px;
      }
    }
  }

  .data-preview {
    width: calc(100% - 200px);
    height: 100%;
    padding-left: 18px;
    box-sizing: border-box;

    .preview-tips {
      width: 100%;
      height: 18px;
      display: flex;
      align-items: center;
      justify-content: flex-end;

      font-size: 12px;
      color: #606266;
    }

    .preview-table {
      height: calc(100% - 18px) !important;
    }
  }
}
</style>
